var colors =new Map();


function getColor2(name) {
    if (colors.has(name))
        return colors.get(name);
    var color = "#";
    for (var i = 0; i < 6; i++) {
        color += (Math.random() * 16 | 0).toString(16);
    }
    colors.set(name, color);
    return color;
}

function DrawTree() {

    let margin = {top: 35, right: 20, bottom: 30, left: 15},
        width = 370,
        height = 1000,
        i = 0,
        nodeSize = 17,
        duration = 500,
        format = d3.format(",")
        columns = [
            {
                label: "Size",
                value: d => d.value,
                format,
                x: 340
            },
            // {
            //     label: "Count",
            //     value: d => d.children ? 0 : 1,
            //     format: (value, d) => d.children ? format(value) : "-",
            //     x: 340
            // }
        ]
    let nodeEnterTransition = d3.transition()
        .duration(750)
        .ease(d3.easeLinear);
    fetch('flare-2.json')
        .then(resp => resp.json())
        .then(data => {

            const root = d3.hierarchy(data).eachBefore(d => d.index = i++)
            const nodeslength = root.descendants();

            const svg = d3.create("svg")
                .attr("viewBox", [-nodeSize / 2, -nodeSize * 3 / 2, width, (nodeslength.length + 1) * nodeSize])
                .attr("font-family", "sans-serif")
                .attr("font-size", 10)
                .style("overflow", "visible");

            function update() {
                const nodes = root.descendants();
                console.log(nodes)

                const node = svg.selectAll(".node")
                    .data(nodes, (d) => d.id || (d.id = ++i));
                console.log(node)

                const link = svg.append("g")
                    .attr("fill", "none")
                    .attr("stroke", "#999")
                    .selectAll("path")
                    .data(root.links())
                    .join("path")
                    .attr("d", d => `
        M${d.source.depth * nodeSize},${d.source.index * nodeSize}
        V${d.target.index * nodeSize}
        h${nodeSize}
      `)
                    .attr("class", d => `link${d.source.index}`);


                const nodeEnter = node.enter().append("g")
                    .attr("class", "node")


                nodeEnter.attr("transform", d => `translate(0,${d.index * nodeSize})`)
                    .on("click", click)

                console.log("ssssssssssssss")
                console.log(nodeEnter)
                nodeEnter.append("circle")
                    .attr("cx", d => d.depth * nodeSize)
                    .attr("r", 3)
                    .attr("fill", d => d.children ? null : "#999")

                // if(d.depth==6||d.depth==7)
                // {
                //     nodeEnter.append("text")
                //         .attr("dy", "0.32em")
                //         .attr("font-style","italic")
                //         .attr("font-size","15px")
                //         .attr("x", d => d.depth * nodeSize + 6)
                //         .text(d => d.data.name)
                //         .on("click2", click2)
                // }
                // else {
                    nodeEnter.append("text")
                        .attr("dy", "0.32em")
                        .attr("font-size", "15px")
                        .attr("font-style",function(d){
                            if(d.depth==6||d.depth==7){
                                return "italic";
                            }
                            return "normal";
                        })
                        .attr("font-weight",function(d){
                            if(d.depth==5){
                                return "bold";
                            }
                            return "normal";
                        })
                        .attr("x", d => d.depth * nodeSize + 6)
                        .text(d => d.data.name)
                        .on("click2", click2)
            // }
                nodeEnter.append("title")
                    .text(d => d.ancestors().reverse().map(d => d.data.name).join("/"));


                for (const {label, value, format, x} of columns) {

                    svg.append("text")
                        .attr("dy", "0.32em")
                        .attr("y", -nodeSize)
                        .attr("x", x)
                        .attr("font-size","15px")
                        .attr("text-anchor", "end")
                        .attr("font-weight", "bold")
                        .text(label)

                    nodeEnter.append("text")
                        .attr("dy", "0.32em")
                        .attr("font-size","15px")
                        .attr("x", x)
                        .attr("text-anchor", "end")
                        .attr("fill", d => d.children ? null : "#555")
                        .data(root.copy().sum(value).descendants())
                        .text(d => format(d.value, d));
                }

                node.exit().transition()
                    .duration(duration)
                    .style("opacity", 0)
                    .remove();

                link.exit().transition()
                    .duration(duration)
                    .style("opacity", 0)
                    .remove();

            }

            function click(d) {
                const allPaths = []
                allPaths.push(d.index)
                if (d.parent) {
                    console.log(d.data.name)
                   DrawPoint(d.data.name)
                    if (d.children) {
                        d._children = d.children
                        d.children = null
                        const allChildren = d.descendants();
                        allChildren[0]['_children'].forEach(function (c) {
                            allPaths.push(c.index);
                            c.descendants().forEach((gc) => {
                                allPaths.push(gc.index);
                            });
                        });
                    } else {
                        d.children = d._children;
                        d._children = null;
                    }
                    allPaths.map(p => d3.selectAll(`path.link${p}`).remove())
                    d3.select(this).remove()
                    update();
                }
            }
            function click2(d) {
                const allPaths = []
                allPaths.push(d.index)
                if (d.parent) {
                   // DrawPoint(d.data.name)
                }
            }

            update()
            document.querySelector('#tree').append(svg.node())
        })

}

function  DrawPoint(name) {
    console.log("向后端发送请求")

    $.ajax({
        type: "GET",
        url: UIL + "/searchtree" + "/"+name ,
        success: function (data) {
            console.log("data",data);
            deleteMarkers();
            function geojsonMarkerOptions(feature) {
                return {
                    fillColor: getColor2(name),
                    weight: 2,
                    opacity: 1,
                    color: 'white',
                    //dashArray: '3',
                    fillOpacity: 0.7
                };
            }

            if(marked==false)
            {
                globalmarkers = L.geoJSON(data,
                    {
                        onEachFeature: onEachFeature,
                        pointToLayer: function (feature, latlng) {
                            //map.removeLayer(markers)
                            markers=L.circleMarker(latlng, geojsonMarkerOptions(feature));
                            return markers;
                        }
                    }).addTo(map);
                marked =true;
            }


        },
            error: function () {
                console.log("失败 ",d.lag);
            }
        });

}
